package com.toolmanrln.security.component;

import cn.hutool.core.util.StrUtil;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ToolMan.RLN
 * @since 2020-05-21 15:28
 */
public class VerifyCodeAuthenticationProvider extends DaoAuthenticationProvider {


    public static final String VERIFY_CODE = "verifyCode";

    /**
     * 附加的认证检查
     *
     * @param userDetails
     * @param authentication
     * @return void
     * @throws
     * @author ToolMan.RLN
     * @date 2020-05-21 15:29
     */
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        checkVerifyCode(request);
        super.additionalAuthenticationChecks(userDetails, authentication);
    }

    /**
     * 校验验证码
     *
     * @param request
     * @return void
     * @throws
     * @author ToolMan.RLN
     * @date 2020-05-25 16:16
     */
    public static void checkVerifyCode(HttpServletRequest request) {
        String postVerifyCode = request.getParameter(VERIFY_CODE);
        String verifyCode = (String) request.getSession().getAttribute(VERIFY_CODE);
        if (StrUtil.isBlank(postVerifyCode)) {
            throw new AuthenticationServiceException("验证码不能为空");
        }
        if (StrUtil.isBlank(verifyCode)) {
            throw new AuthenticationServiceException("请刷新验证码");
        }
        postVerifyCode = postVerifyCode.toLowerCase();
        verifyCode = verifyCode.toLowerCase();
        if (!StrUtil.equals(postVerifyCode, verifyCode)) {
            throw new AuthenticationServiceException("验证码不正确");
        }
    }
}
